package org.mzy.org.service.impl;

import org.mzy.basic.service.impl.BaseServiceImpl;
import org.mzy.org.domain.Department;
import org.mzy.org.domain.Employee;
import org.mzy.org.mapper.DepartmentMapper;
import org.mzy.org.service.IDepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Package: org.mzy.org.service.impl
 * @ClassName: DeparmentImpl
 * @Date:2022/9/28 11:06
 * @Description:
 */
@Service
@Transactional(readOnly = true, propagation = Propagation.SUPPORTS)
public class DeparmentImpl extends BaseServiceImpl<Department> implements IDepartmentService {
    @Autowired
    private DepartmentMapper departmentMapper;

    // 分级查询
    @Override
    public List<Department> deptTree() {
        List<Department> result = new ArrayList<>();
        List<Department> allDepts = departmentMapper.findAll();
        if (CollectionUtils.isEmpty(allDepts)) {
            return result;
        }
        // stream
        Map<Long, Department> parentMap = allDepts.stream().collect(Collectors.toMap(Department::getId, e -> e));
        // 同理
        // 遍历
        for (Department dept : allDepts) {
            if (null == dept.getParentId()) {
                // 它就是最大的那个die
                result.add(dept);
            } else {
                // 当前的这个dept 是个儿子
                // 找爹 自己是个儿子 有爹的id
                Department parent = parentMap.get(dept.getParentId());
                if (null == parent) {
                    break;
                }
                List<Department> children = parent.getChildren();
                children.add(dept);
            }
        }
        System.out.println(result);
        return result;
    }

    @Override
    public List<Employee> findEmpById(Long id) {
        return null;
    }
}
